<template>
  <page-header-wrapper>
    <page-tab-list></page-tab-list>
    <a-card :bordered="false">
      <div class="table-operator" style="float: right">
          <a-button type="primary" @click="onEdit" icon="plus">新增</a-button>
      </div>
      <a-divider />
      <a-table ref="table" size="default" row-key="id" :columns="columns" :data-source="loadData" :pagination="false">
        <a-switch
          slot="is_enable"
          checked-children="开启"
          un-checked-children="关闭"
          slot-scope="is_enable, item"
          :default-checked="is_enable > 0"
          @change="onConfirmStatus('is_enable', item.id)"
        />
        <span slot="action" slot-scope="text, item">
          <a-button type="link" @click="onEdit(item.id)" size="small">编辑</a-button>
      <a-divider type="vertical"/>
          <a-button type="link" @click="onConfirmStatus('is_delete', item.id)" size="small">删除</a-button>
        </span>
      </a-table>
    </a-card>
    <a-modal title="规则详情" v-model="popPostage" @ok="onSave" :width="700">
      <a-form-model ref="ruleForm" :model="postage" :rules="rules" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }">
        <a-form-model-item label="规则名称" prop="name">
          <a-input v-model="postage.name" placeholder="请输入名称"></a-input>
        </a-form-model-item>
        <a-form-model-item label="计费方式" prop="type">
          <a-radio-group
            v-model="postage.type"
            @change="
              () => {
                this.province_list = []
                this.data = [
                  {
                    frist: '',
                    frist_price: '',
                    second: '',
                    second_price: '',
                    min_weight: '',
                    max_weight: '',
                  },
                ]
                this.checkedList = []
              }
            "
          >
            <a-radio :value="1"> 按重计费</a-radio>
            <a-radio :value="2"> 按件计费</a-radio>
          </a-radio-group>
        </a-form-model-item>
        <a-form-model-item label="运费规则">
          <a-card
            v-for="(province, index) in province_list"
            size="small"
            :key="index"
            style="margin-bottom: 10px; max-height: 500px; overflow-y: scroll"
          >
            <a-button slot="extra" size="small" @click="delProvince(index)">删除</a-button>
            <a-row>
              <a-table :columns="getTableAttr" :data-source="province.rules" size="small" :pagination="false">
                <span slot="frist" slot-scope="text">
                  {{ text.frist }}
                </span>
                <span slot="frist_price" slot-scope="text">
                  {{ text.frist_price }}
                </span>
                <span slot="second" slot-scope="text">
                  {{ text.second }}
                </span>
                <span slot="second_price" slot-scope="text">
                  {{ text.second_price }}
                </span>
                <span slot="province" slot-scope="text, record">
                  {{ record.min_weight }} ~ {{ record.max_weight }}
                </span>
              </a-table>
            </a-row>
            <a-row type="flex">
              <span
                style="margin-right: 10px"
                v-for="(item, index1) of province.province_list"
                :key="index + '' + index1"
              >
                {{ item.name }}
              </span>
            </a-row>
          </a-card>
          <a-button @click="showInfo" icon="plus" size="small"> 新增条目</a-button>
        </a-form-model-item>
      </a-form-model>
    </a-modal>

    <a-modal
      v-model="showInfoStatus"
      :afterClose="closeModal"
      v-if="district.length > 0"
      :width="700"
      title="添加运费规则"
      @ok="handleOk"
    >
      <a-table :columns="getTableAttr" :data-source="data" size="small" :pagination="false">
        <span slot="frist" slot-scope="text, record">
          <a-input size="small" type="number" style="text-align: center" placeholder="" v-model="record.frist" />
        </span>
        <span slot="frist_price" slot-scope="text, record">
          <a-input size="small" type="number" style="text-align: center" placeholder="" v-model="record.frist_price" />
        </span>
        <span slot="second" slot-scope="text, record">
          <a-input size="small" type="number" style="text-align: center" placeholder="" v-model="record.second" />
        </span>
        <span slot="second_price" slot-scope="text, record">
          <a-input size="small" type="number" style="text-align: center" placeholder="" v-model="record.second_price" />
        </span>
        <span slot="province" slot-scope="text, record">
          <div style="display: flex; align-items: center">
            <a-input size="small" type="number" style="text-align: center" placeholder="" v-model="record.min_weight" />
            ~
            <a-input size="small" type="number" style="text-align: center" placeholder="" v-model="record.max_weight" />
          </div>
        </span>
      </a-table>
      <div style="display: flex; justify-content: flex-end">
        <a-button
          v-if="(postage.type == 2 && data.length < 1) || postage.type != 2"
          @click="
            data.push({
              frist: '',
              frist_price: '',
              second: '',
              second_price: '',
              min_weight: '',
              max_weight: '',
            })
          "
        >新增项
        </a-button>
      </div>

      <a-row>
        <a-tree
          style="display: flex; flex-wrap: wrap"
          :blockNode="true"
          :checkable="true"
          @check="(e) => onSelectCheck(e)"
          multiple
        >
          <a-tree-node
            v-for="province of getDistrict"
            :style="{ width: '33%', display: 'flex', flexWrap: 'wrap' }"
            :key="JSON.stringify({ id: province.id, name: province.name, type: 'province' })"
            :title="province.name"
          >
            <template v-for="city of province.cityAll">
              <a-tree-node
                v-if="showTreeItem(city.id)"
                :isLeaf="true"
                :key="JSON.stringify({ id: city.id, name: city.name, type: 'city' })"
                :title="city.name"
              >
              </a-tree-node>
            </template>
          </a-tree-node>
        </a-tree>
      </a-row>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { List, Edit, Save, Status } from '@/api/setting/postage'
import { STable } from '@/components'
import { savePostage } from '@/api/purchase/supplier'

const columns = [
  {
    title: '规则名称',
    dataIndex: 'name',
  },
  {
    title: '是否默认',
    dataIndex: 'is_enable',
    scopedSlots: { customRender: 'is_enable' },
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '150px',
    scopedSlots: { customRender: 'action' },
  },
]

const tableColumns = [
  {
    scopedSlots: { customRender: 'frist' },
  },
  {
    title: '首费（元）',
    scopedSlots: { customRender: 'frist_price' },
  },
  {
    scopedSlots: { customRender: 'second' },
  },
  {
    title: '续费（元）',
    scopedSlots: { customRender: 'second_price' },
  },
  {
    title: '范围（重量克）',
    scopedSlots: { customRender: 'province' },
  },
]

export default {
  name: 'PostageList',
  components: {
    STable,
  },
  data() {
    return {
      columns: columns,
      loading: false,
      visible: false,
      showInfoStatus: false, // 是否展示地区
      province_list: [],
      postage: { name: '', type: 1 },
      district: [],
      selectData: [], // 选中的数据
      priceData: {
        frist: 1,
        frist_price: 0,
        second: 1,
        second_price: 0,
      }, // 金额配置
      loadData: [],
      popPostage: 0,
      data: [
        {
          frist: '',
          frist_price: '',
          second: '',
          second_price: '',
          min_weight: '',
          max_weight: '',
        },
      ],
    }
  },
  created() {
    this.getList()
  },
  computed: {
    getTableAttr() {
      let attr = JSON.parse(JSON.stringify(tableColumns))
      attr.forEach((el, index) => {
        switch (index) {
          case 0:
            el.title = this.postage.type != 2 ? '首重（克）' : '首件（个）'
            break
          case 2:
            el.title = this.postage.type != 2 ? '续重（克）' : '续件（个）'
            break
          case 4:
            if (this.postage.type == 2) {
              attr.splice(4, 1)
            }
            break
        }
      })

      return attr
    },

    getDistrict() {
      return this.district.filter((el) => {
        let list = []

        el.cityAll.forEach((e) => {
          if (this.checkedList.indexOf(e.id) === -1) {
            list.push(e)
          }
        })

        return list.length
      })
    },

    showTreeItem() {
      return (id) => {
        return this.checkedList.indexOf(id) === -1
      }
    },
  },
  methods: {
    getList(parameter) {
      this.loadData = null
      return List(parameter).then((res) => {
        this.loadData = res.data.list
      })
    },
    onEdit(id) {
      this.popPostage = true
      this.selectData = []
      this.province_list = []
      this.checkedList = []
      Edit({ id: id }).then((res) => {

        this.loading = false

        this.province_list = res.data.model ? JSON.parse(res.data.model.detail) : []
        this.postage = res.data.model ? res.data.model : { type: 1, name: '' }
        this.province_list.forEach((el) => {
          el.province_list.forEach((e) => {
            this.checkedList.push(e.id)
          })
        })
        this.district = res.data.district
      })

      if (!id) {
        this.postage = {
          type: 1,
          name: '',
        }
      }
    },
    onSave(id) {
      this.$refs['ruleForm'].validate(async (valid) => {
        if (valid) {
          let { postage } = this
          let param = {
            postage: {
              ...postage
            },
            province_list: JSON.stringify(this.province_list),
          }
          const res = await Save(param)

          if (res.code === 0) {
            this.$message.success('保存成功~')
            this.popPostage = false
            this.getList();
          } else {
            this.$message.error(res.msg)
          }
        } else {
          return false
        }
      })
      // if (this.postage.name) {
      //   this.$message.loading({ content: '提交中', key: 'updatable' })
      //   Save({ postage: this.postage, province_list: this.province_list }).then((res) => {
      //     if (res.code === 0) {
      //       this.$message.success({ content: res.msg, key: 'updatable' })
      //       this.$nextTick(() => {
      //         this.visible = false
      //         this.selectData = []
      //         this.province_list = []
      //         this.getList()
      //       })
      //     } else {
      //       this.$message.error({ content: res.msg, key: 'updatable' })
      //     }
      //   })
      // } else {
      //   this.$message.error('请填写名称')
      // }
    },
    onClose() {
      this.visible = false
      this.loading = false
      this.province_list = []
      this.district = []
      this.postage = { name: '' }
    },
    typeChange(value) {
      this.postage.type = value
      this.province_list = []
    },
    onSelectCheck(value) {
      var arr = []
      value.forEach((element) => {
        if (JSON.parse(element).type === 'city') {
          arr.push(JSON.parse(element))
        }
      })
      this.selectData = arr
    },
    showInfo() {
      this.showInfoStatus = true
    },
    handleOk() {
      let checkedList = this.selectData.map((el) => el.id)

      checkedList.forEach((el, i) => {
        if (this.checkedList.indexOf(el) === -1) {
          this.checkedList.push(el)
        } else {
          this.selectData.splice(i, 1)
        }
      })
      let rules = this.data
      var data = {
        rules: rules,
        province_list: this.selectData,
      }
      this.province_list.push(data)
      this.showInfoStatus = false
      this.data = [
        {
          frist: '',
          frist_price: '',
          second: '',
          second_price: '',
          min_weight: '',
          max_weight: '',
        },
      ]
    },
    onConfirmStatus(type, id) {
      if (type === 'is_delete') {
        var that = this
        this.$confirm({
          content: '是否确认删除',
          onOk() {
            that.updateStatus({ id: id, type: type })
          },
        })
      } else {
        this.updateStatus({ id: id, type: type })
      }
    },
    updateStatus(q) {
      Status(q).then((res) => {
        if (res.code === 0) {
          this.getList()
          this.$message.success(res.msg)
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    delProvince(index) {
      this.province_list.splice(index, 1)
    },
  },
}
</script>
<style lang="less" scoped>
.required::before {
  content: '*';
  color: red;
}
</style>
